import 'dart:async';

import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/model.dart';

/// 做题界面
class EducationQuizController extends GetxController {
  /// 构造器
  EducationQuizController(this.config) {
    if (!watchTime || config.leftSeconds <= 0) return;
    timer = Timer.periodic(const Duration(seconds: 1), (_) {
      if (timer == null) return;
      if (config.leftSeconds <= 0) {
        _disposeTimer();
        if (!isFinished) config.onFinish();
        //update();
        return;
      }
      config.leftSeconds--;
      update();
    });
  }

  /// 如果为计时考试，则不为 null
  Timer? timer;

  void _disposeTimer() {
    timer?.cancel();
    timer = null;
  }

  @override
  void onClose() {
    super.onClose();
    _disposeTimer();
  }

  /// 所有的题目的配置
  final QuizConfig config;

  /// 题目界面字体显示大小
  final textSize = QuizTextSize.small.obs;

  /// 考试是否完成
  bool get isFinished => config.isFinished;

  /// 当前题目的索引
  var currentQuizIdx = 0;

  /// 当前的题目
  QuizTopic get currentQuiz => quizs[currentQuizIdx];

  /// 所有题目
  List<QuizTopic> get quizs => config.topics;

  /// 是否计时
  bool get watchTime => config.type.watchTime;

  /// 选项点击时调用
  void selectOption(String option) {
    if (config.isFinished) return;
    final idx = currentQuiz.options.indexOf(option);
    if (idx == -1) {
      return;
    }
    final currentSelectList = currentQuiz.selectedIdx;
    if (currentSelectList.contains(idx)) {
      currentSelectList.remove(idx);
    } else {
      if (currentQuiz.answers.length == 1) {
        currentSelectList.clear();
      }
      currentSelectList.add(idx);
    }
    update();
  }

  /// 0 -> A
  String idx2Str(int idx) {
    return String.fromCharCode(65 + idx);
  }

  /// 左右滑动切换题目 调用
  void onSlide(bool left, bool right) {
    if (!left && !right) return;
    if (left) {
      if (currentQuizIdx > 0) {
        currentQuizIdx--;
      } else {
        return;
      }
    } else {
      if (currentQuizIdx < quizs.length - 1) {
        currentQuizIdx++;
      } else {
        return;
      }
    }
    update();
  }

  /// 剩余时间，转换
  QuizLeftTime get leftTime {
    final left = config.leftSeconds;
    final hours = left ~/ 3600;
    final minutes = (left % 3600) ~/ 60;
    final seconds = left % 60;
    return QuizLeftTime(hours: hours, minutes: minutes, seconds: seconds);
  }
}
